import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:village_android/config/contants.dart';
import 'package:village_android/main.dart';
import 'package:village_android/pages/auth/register_first_page.dart';
import 'package:village_android/pages/auth/register_page.dart';
import 'package:village_android/utils/common_utils.dart';
import 'package:village_android/utils/http_utlis.dart';
import 'package:village_android/utils/store_utils.dart';
import 'dart:convert' as convert;

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => new _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _formKey = GlobalKey<FormState>();
  Color _eyeColor;
  bool _isClickEye = false;
  String _userName;
  String _pwd;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text("智慧党建 阳光北亭",
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.white)),
          actions: <Widget>[
            new IconButton(
                icon: new Icon(Icons.close),
                tooltip: '返回主页',
                onPressed: () {
                  Navigator.of(context).pushNamedAndRemoveUntil(
                      "/home", ModalRoute.withName("/home"));
                }),
          ],
        ),
        body: Container(
          padding: EdgeInsets.all(20),
          child: Form(
            key: _formKey,
            child: ListView(
              children: <Widget>[
                SizedBox(height: 10),
                Container(
                  padding: EdgeInsets.only(left: 0.0),
                  child: Image.network(
                    "http://s.mmbb123.com/%E5%9B%BE%E7%89%871.jpg",
                    height: 220,
                    fit: BoxFit.fill,
                  ),
                ),
                SizedBox(height: 10.0),
                initLoginName(),
                SizedBox(height: 30.0),
                initLoginPWD(),
                SizedBox(height: 50.0),
                initButton(),
                initRegister(),
                SizedBox(height: 10.0),
                initReset(),
                SizedBox(height: 100.0),
              ],
            ),
          ),
        ));
  }

  Padding initTitle() {
    return Padding(
      padding: EdgeInsets.all(10),
      child: Text(
        '阳光北亭-登陆',
        style: TextStyle(
            fontSize: 30.0,
            color: Colors.deepOrange,
            fontWeight: FontWeight.bold),
        textAlign: TextAlign.center,
      ),
    );
  }

  Padding initHorizontalLine() {
    return Padding(
        padding: EdgeInsets.only(top: 10.0, bottom: 10.0),
        child: Align(
          alignment: Alignment.bottomCenter,
          child: Container(
            color: Colors.deepOrange,
            width: 100,
            height: 2,
          ),
        ));
  }

  TextFormField initLoginName() {
    return TextFormField(
      onSaved: (String value) => _userName = value,
//      maxLength: 11,
      decoration: InputDecoration(labelText: '手机号码'),
//      validator: (String value){
//        var isPhone = RegExp("^1[3456789][0-9]{9}");
//        if(!isPhone.hasMatch(value)){
//          return '用户名格式不正确';
//        }
//      },
    );
  }

  TextFormField initLoginPWD() {
    return TextFormField(
      obscureText: _isClickEye,
      onSaved: (String value) => _pwd = value,
      validator: (String value) {
        if (value.isEmpty) {
          return '密码不能为空';
        }
      },
      decoration: InputDecoration(
        labelText: '密码',
        suffixIcon: IconButton(
            icon: Icon(Icons.remove_red_eye, color: _eyeColor),
            onPressed: () {
              setState(() {
                _isClickEye = !_isClickEye;
                _eyeColor = _isClickEye ? Colors.grey : Colors.blue;
              });
            }),
      ),
    );
  }

  Align initButton() {
    return Align(
      child: SizedBox(
        width: 300.0,
        height: 50.0,
        child: RaisedButton(
          child: Text("登录",
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.white)),
          color: Colors.red,
          onPressed: () {
            //CommonUtils.showToast(context, '登录');
            if (_formKey.currentState.validate()) {
              _formKey.currentState.save();
            }
            toLogin();
          },
          shape: StadiumBorder(side: BorderSide(color: Colors.red)),
        ),
      ),
    );
  }

  Future toLogin() async {
    FormData formData = new FormData.from({
      "username": _userName.toString(),
      "password": _pwd,
    });

    HttpUtils.postForm("/api/auth", formData: formData, context: context,
        success: (data) {
      CommonUtils.showToast(context, "登录成功");
      String jsonString = convert.jsonEncode(data);
      SharedPreferenceUtil.save(SharedPreferenceUtil.KEY_USERMODEL, jsonString);
      sp.setString(K_USER_ID, data[K_USER_ID].toString());
      new Future.delayed(
          const Duration(seconds: 1),
          () => {
                Navigator.of(context).pushNamedAndRemoveUntil(
                    "/home", ModalRoute.withName("/home"))
              });
    }, error: (errorMsg) {
      CommonUtils.showToast(context, errorMsg);
    });
  }

  Padding initRegister() {
    return Padding(
      padding: EdgeInsets.only(top: 10.0),
      child: GestureDetector(
        child: Align(
          alignment: Alignment.center,
          child: Text('没有账号？点击注册'),
        ),
        onTap: () {
          var page = RegisterPage();
          Navigator.push(
              context, new MaterialPageRoute(builder: (context) => page));
        },
      ),
    );
  }

  Padding initReset() {
    String phone = "";
    return Padding(
      padding: EdgeInsets.only(top: 10.0),
      child: GestureDetector(
        child: Align(
          alignment: Alignment.center,
          child: Text('重置密码'),
        ),
        onTap: () {
          showDialog(
              context: context,
              builder: (_) => new AlertDialog(
                      title: new Text("是否重置密码为6个1"),
                      content: new Row(
                        children: <Widget>[
                          new Expanded(
                              child: new TextField(
                            controller: TextEditingController()
                              ..text = phone,
                            autofocus: true,
                            decoration: new InputDecoration(
                                labelText: '输入手机账号', hintText: '如：13182829991'),
                            onChanged: (value) {
                              phone = value;
                            },
                          ))
                        ],
                      ),
                      actions: <Widget>[
                        new FlatButton(
                          child: new Text("取消"),
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                        ),
                        new FlatButton(
                          child: new Text("确定"),
                          onPressed: () {
                            FormData formData = new FormData.from({
                              "phone": phone,
                            });
                            HttpUtils.postForm("/mgr/resetByPhone",
                                formData: formData,
                                context: context, success: (data) {
                              CommonUtils.showToast(context, "修改成功");
                            }, error: (errorMsg) {
                              CommonUtils.showToast(context, errorMsg);
                            });
                          },
                        )
                      ]));
        },
      ),
    );
  }
}
